<template>
  <div class="dialog-form">
    <el-dialog v-model="formVisible" title="设置护理员" @close="onClickCloseBtn">
      <div class="dialogCenter">
        <el-form ref="formRef" :label-width="120" :model="formData" :rules="rules">
          <el-form-item label="护理员姓名：" prop="bedNumber">
            <el-select v-model="formData.bedNumber" class="wt-400" multiple placeholder="请选择">
              <el-option v-for="item in data" :key="item.userId" :label="item.nickName" :value="item.userId">
                {{ item.nickName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="onClickCloseBtn">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {watch} from 'vue';

const {proxy} = getCurrentInstance();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  singleNurse: {
    type: Object,
    default: () => {
      return [];
    },
  },
});
// 触发父级事件
const emit = defineEmits(['handleClose', 'handleSubmit']);
const resetType = ref('empty');
const formRef = ref(null);
const formVisible = ref(false);
const formData = ref({});

const rules = {
  bedNumber: [
    {
      required: true,
      message: '护理员姓名为空，请选择护理员姓名',
      type: 'error',
      trigger: 'blur',
    },
    {
      validator: (val) => {
        if (val && val.length < 0) {
          return {
            result: false,
            message: '请选择护理员姓名',
            type: 'error',
          };
        }
        return true;
      },
    },
  ],
};

watch(
    () => props.visible,
    () => {
      formVisible.value = props.visible;
      formData.value.bedNumber = props.singleNurse;
    }
);

watch(
    () => formData.value.bedNumber,
    (val) => {
      if (val.length > 4) {
        formData.value.bedNumber = val.slice(0, 4);
      }
    }
);

// 提交表单
const onSubmit = () => {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      emit('handleSubmit', formData.value.bedNumber);
    }
  });
};

const handleChange = (val) => {
  formData.value.bedNumber = val;
};

// 清除表单数据
const handleClear = () => {
  formRef.value.resetFields();
};

// 点击取消关闭
const onClickCloseBtn = () => {
  handleClear();
  emit('handleClose');
};

defineExpose({
  handleClear,
});
</script>
